/*
 * Copyright (c) 2009.
 */

package kz.home;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreException;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: danik
 * Date: 15.07.2009
 * Time: 1:49:50
 * To change this template use File | Settings | File Templates.
 */
public class phoneTest extends MIDlet {
    private String db = "MYDB1";

    protected void startApp() throws MIDletStateChangeException {
        try {

            write();
        } catch ( Exception e) {
            e.printStackTrace();
        }

        try {
            System.out.println("[" + read() + "]");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String read() throws RecordStoreException, IOException {
        ByteArrayInputStream stream;
        DataInputStream reader;
        String fname = null;

        RecordStore store = RecordStore.openRecordStore(db, true );
        for (int i = 1; i <= store.getNumRecords(); i++) {
            byte[] rec = new byte[store.getRecordSize(i)];
            stream = new ByteArrayInputStream(rec);
            reader = new DataInputStream(stream);
            fname = reader.readUTF();
        }
        return fname;
    }

    private void write() throws IOException, RecordStoreException {
        int recordID = 0;
        ByteArrayOutputStream bytstream = new ByteArrayOutputStream();
        DataOutputStream writer = new DataOutputStream(bytstream);

        writer.writeUTF("Даник");
        writer.writeUTF("Leo");
        writer.writeUTF("Fernandes");
        writer.writeUTF("1500 Dec Road,UC,CA 94545");
        writer.writeUTF("5107776666");
        writer.flush();

        byte[] rec = bytstream.toByteArray();
        RecordStore store = RecordStore.openRecordStore(db, true);
        store.addRecord(rec, 0, rec.length);
        bytstream.reset();

        /*//Second Record
        writer.writeUTF("Raj");
        writer.writeUTF("Malhotra");
        writer.writeUTF("1501 Dec Road,UC,CA 94545");
        writer.writeUTF("5107775454");
        writer.flush();

        rec = bytstream.toByteArray();
        store.addRecord(rec, 0, rec.length);

        System.out.println("recordID [" + recordID + "]");*/
        writer.close();
        bytstream.close();
    }

    protected void pauseApp() {

    }

    protected void destroyApp(boolean b) throws MIDletStateChangeException {

    }
}
